<?php

namespace app\common\service;

use app\common\library\ReturnResult;
use app\common\model\TaskOperateLog;
use app\common\model\User;
use think\Db;

class Base
{
    use ReturnResult;

    /**
     * 是否开启记录调试的日志
     *
     * @var boolean
     */
    protected $openRecord = true;

    /**
     * 调用该接口的用户来源渠道
     * 可选值：auto(其他服务器触发)、user、promoter、master、admin, super(后台管理员)
     * @var string
     */
    protected $channel = 'user';

    /**
     * 调用该接口的用户id
     *
     * @var integer
     */
    protected $uid = 0;

    public function __construct($uid = 0, $channel = 'user')
    {
        $this->channel = $channel;
        $this->uid = $uid;
    }

    /**
     * 检测用户是否有权限进行后续的接口操作
     *
     * @return bool
     */
    public function checkAuth($tableName = '', $id = 0, $field = 'uid')
    {
        try {
            //来自后台的操作则不用进行下一步的权限检测，直接返回
            if ($this->channel == 'super') {
                return true;
            }
            //检测用户是否是管理员、师傅、推广员
            if ($this->channel != 'user' && false === User::checkUserType($this->uid, $this->channel)) {
                return false;
            }

            //来自小程序端的管理员
            if ($this->channel == 'admin') {
                return true;
            }

            //进一步检测用户是否有该条数据的操作权限
            if (!empty($tableName)) {
                $info = Db::name($tableName)->where('id', $id)->where($field, $this->uid)->value('id');
                return !empty($info);
            }

            return true;
        } catch (\Exception $e) {
            recordExceptionInfo($e);
            return false;
        }
    }

    /**
     * 记录作业任务相关的操作日志
     *
     * @param integer $opeate_type 操作类型 1作业任务 2派单明细 3作业打卡
     * @param string $opeate_desc  操作说明
     * @return bool
     */
    protected function saveTaskOperateLog($opeate_type = 1, $opeate_desc = '')
    {
        $data = [
            'uid' => $this->uid,
            'admin_id' => $this->uid,
            'utype' => $this->channel == 'super' ? 1 : 2,
            'opeate_type' => $opeate_type,
            'opeate_desc' => $opeate_desc
        ];
        $res = TaskOperateLog::create($data);
        return !empty($res);
    }
}
